package model

import (
	"fmt"

	//"github.com/jinzhu/gorm"
	//_ "github.com/jinzhu/gorm/dialects/mysql"
	//"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)

type Database struct {
	Self *tablestore.TableStoreClient
}

// 单例
var DB *Database

func (db *Database) Init() {
	DB = &Database{
		Self: GetDB(),
	}
}

func (db *Database) Close() {
	//DB.Self.Close()
}

func openDB(endpoint, instanceName, accessKeyId, accessKeySecret string) *tablestore.TableStoreClient {
	client := tablestore.NewClient(endpoint, instanceName, accessKeyId, accessKeySecret)
	//setupDB(db)
	return client
}

//func setupDB(db *tablestore.TableStoreClient) {
//	db.LogMode(viper.GetBool("gormlog"))
//	// 用于设置最大打开的连接数，默认值为0表示不限制.设置最大的连接数，可以避免并发太高导致连接mysql出现too many connections的错误。
//	//db.DB().SetMaxOpenConns(20000)
//	// 用于设置闲置的连接数.设置闲置的连接数则当开启的一个连接使用完成后可以放在池里等候下一次使用。
//	db.DB().SetMaxIdleConns(0)
//}

func InitDB() *tablestore.TableStoreClient {
	viper.SetConfigName("config") // name of config file (without extension)
	viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
	viper.AddConfigPath("/home/go/otss/")   // path to look for the config file in
	//viper.AddConfigPath("$HOME/.appname")  // call multiple times to add many search paths
	//viper.AddConfigPath(".")               // optionally look for config in the working directory
	err := viper.ReadInConfig() // Find and read the config file
	if err != nil { // Handle errors reading the config file
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	fmt.Println(viper.GetString("db.OTS_TEST_ENDPOINT"))
	return openDB(
		viper.GetString("db.OTS_TEST_ENDPOINT"),
		viper.GetString("db.OTS_TEST_INSTANCENAME"),
		viper.GetString("db.OTS_TEST_KEYID"),
		viper.GetString("db.OTS_TEST_SECRET"),
	)
}

func GetDB() *tablestore.TableStoreClient {
	return InitDB()
}
